<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图片名称">
        <el-input v-model="queryParams.name" placeholder="请输入图片名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文件名称">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="属性名称">
        <el-input v-model="queryParams.propertyName" placeholder="请输入属性名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="系列名称">
        <el-input v-model="queryParams.seriesName" placeholder="请输入系列名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="备注1" prop="remark1">
        <el-input v-model="queryParams.remark1" placeholder="请输入备注1" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备注2" prop="remark2">
        <el-input v-model="queryParams.remark2" placeholder="请输入备注2" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备注3" prop="remark3">
        <el-input v-model="queryParams.remark3" placeholder="请输入备注3" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="batch_generate_images_fun" v-hasPermi="['system:images:add']">批量生成图片</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:images:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:images:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:images:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:images:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="imagesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图片 ID" align="center" prop="id" />
      <el-table-column label="图片名称" align="center" prop="name" />
      <el-table-column label="文件 IDS" align="center" prop="fileIds" />
      <el-table-column label="图片路径" align="center" prop="path" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.path" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="图片信息名" align="center" prop="message" />
      <el-table-column label="系列id" align="center" prop="seriesId" />
      <el-table-column label="系列名称" align="center" prop="seriesName" />
      <el-table-column label="文件id" align="center" prop="fileId" />
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <el-table-column label="属性id" align="center" prop="propertyId" />
      <el-table-column label="属性名称" align="center" prop="propertyName" />
      <el-table-column label="备注1" align="center" prop="remark1" />
      <el-table-column label="备注2" align="center" prop="remark2" />
      <el-table-column label="备注3" align="center" prop="remark3" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:images:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:images:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改保存图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70vw" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入图片名称" />
        </el-form-item>
        <el-form-item label="图片路径" prop="path">
          <!-- <image-upload v-model="form.path" /> -->
          <div>{{ form.path }}</div>
          <image-preview :src="form.path" :width="100" :height="100" />
        </el-form-item>
        <!-- <el-form-item label="图片信息名" prop="message">
          <el-input v-model="form.message" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-form-item label="系列">
          <Series_sx @popfun="popfun_data" :series_model='form.seriesId' />
        </el-form-item>
        <div class="property_css">
          <div class="property_css_1">属性</div>
          <div class="property_css_2">
            <div class="property_css_2_1" v-for="(a,b ) in seriesIdlistProperty" :key="b" @click="seriesIdlistProperty_fun(a)"><el-button size="mini">{{ a.name }}</el-button></div>
          </div>
          <div class="property_css_3">
            <div class="property_css_3_1">属性图片</div>
            <div class="property_css_3_2" v-for="(a,b ) in propertyIdlistFile" :key="b" @click="propertyIdlistFile_fun(a)">
              <div class="property_css_3_2_1"><el-button size="mini">{{ a.name }}</el-button></div>
              <div class="property_css_3_2_2"><image-preview :src="a.path" :width="70" :height="70" /></div>
            </div>
          </div>
          <div class="property_css_4">
            <div class="property_css_4_1">已选属性图片</div>
            <div class="property_css_4_2" v-for="(a,b ) in propertyIdlistFile_img_arr" :key="b">
              <div class="property_css_4_2_1" @click="propertyIdlistFile_img_arr_fun(a)"><el-button size="mini">{{ a.name }}</el-button></div>
              <div class="property_css_4_2_2"><image-preview :src="a.path" :width="70" :height="70" /></div>
            </div>
          </div>
        </div>
        <div class="property_cs1" @click="downloadImage"><el-button type="primary">生成图片</el-button></div>
        <div class="property_cs2" @click="captureElementAsFile"><el-button type="primary">保存图片</el-button></div>
        <div class="property_cs3" style="width: 500px; height: 500px; position: relative;" ref="do_img">
          <img v-for="(img, index) in propertyIdlistFile_img_arr" :src="realSrc(img.path)" :key="index" style="position: absolute;width: 500px; height: 500px ;" :style="{zIndex: img.remark2  }" />
        </div>

        <el-form-item label="备注1" prop="remark1">
          <el-input v-model="form.remark1" placeholder="请输入备注1" />
        </el-form-item>
        <!-- <el-form-item label="备注2" prop="remark2">
          <el-input v-model="form.remark2" placeholder="请输入备注2" />
        </el-form-item>
        <el-form-item label="备注3" prop="remark3">
          <el-input v-model="form.remark3" placeholder="请输入备注3" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listImages, getImages, delImages, addImages, updateImages } from "@/api/system/images";
// import { listSeries } from "@/api/system/series"; // 查询系列
import { listProperty } from "@/api/system/property";   // 查询系列下的属性
import { listFile } from "@/api/system/file"; // 查询属性对应文件


import html2canvas from 'html2canvas'
import { isExternal } from "@/utils/validate";
import { system_common_upload } from "@/api/system/user";



export default {
  name: "Images",
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],

      // 查询系列对应的属性
      seriesIdlistProperty: [],
      // 查询的属性图片
      propertyIdlistFile: [],
      // 选中的图片
      propertyIdlistFile_img_arr: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保存图表格数据
      imagesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        fileIds: null,
        path: null,
        message: null,
        seriesId: null,
        seriesName: null,
        fileId: null,
        fileName: null,
        propertyId: null,
        propertyName: null,
        remark1: null,
        remark2: null,
        remark3: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created () {
    this.getList();
  },
  watch: {
    // 使用字符串来指定要监听的对象属性  
    'form.seriesId': {
      // 开启深度监听  
      deep: true,
      handler (newVal, oldVal) {
        // 当 form.seriesId 变化时，这个函数会被调用  
        if (newVal) {
          listProperty({ seriesId: newVal }).then(response => {
            this.seriesIdlistProperty = response.rows;
          });
        }
      }
    }
  },

  methods: {
    batch_generate_images_fun () {
      /** 查询文件列表 */
      listFile({
        pageNum: 1,
        pageSize: 999,
      }).then(response => {
        console.log(response.rows, 'listFile');
        let arr = this.reorganizeObjects(response.rows)
        console.log(arr, 'resultresult');
        // this.total = response.total;
        // this.loading = false;
      });
    },
    reorganizeObjects (inputList) {
      const seriesDict = {};
      // 遍历输入列表
      inputList.forEach(obj => {
        const seriesId = obj.seriesId;
        // 如果 seriesId 不存在于字典中，则创建一个新的条目
        if (!seriesDict[seriesId]) {
          seriesDict[seriesId] = {
            seriesId: seriesId,
            seriesName: obj.seriesName,
            propertyarr: [],
            imgarr: []
          };
        }
        // 将当前对象添加到对应的 propertyarr 数组中
        seriesDict[seriesId].propertyarr.push(obj);
      });
      // 遍历 seriesDict 中的每个 seriesId
      for (let seriesId in seriesDict) {
        const propertyarr = seriesDict[seriesId].propertyarr;
        const imgarr = [];
        // 组合所有可能的组合
        for (let i = 0; i < propertyarr.length; i++) {
          const currentObj = propertyarr[i];
          const currentPropertyId = currentObj.propertyId;
          const currentGroup = [currentObj];
          const usedPropertyIds = new Set([currentPropertyId]);
          for (let j = 0; j < propertyarr.length; j++) {
            if (i !== j) {
              const otherObj = propertyarr[j];
              const otherPropertyId = otherObj.propertyId;
              if (!usedPropertyIds.has(otherPropertyId)) {
                currentGroup.push(otherObj);
                usedPropertyIds.add(otherPropertyId);
              }
            }
          }

          // 将当前组合放入 imgarr 数组中
          imgarr.push(currentGroup);
        }

        // 更新 seriesDict 中的 imgarr
        seriesDict[seriesId].imgarr = imgarr;
      }

      // 将字典中的值转换为数组，并返回
      return Object.values(seriesDict);
    }
    ,

    popfun_data (e) {
      this.reset();
      this.form.seriesId = e.id
      this.form.seriesName = e.name
      // 查询系列对应的属性
      listProperty({ seriesId: e.id }).then(response => {
        this.seriesIdlistProperty = response.rows;
        console.log(response.rows, 'listProperty');
      });
    },
    propertyIdlistFile_req (e) {
      /** 查询文件列表 */
      listFile({ propertyId: e }).then(response => {
        console.log(response.rows, 'response.rows');
        this.propertyIdlistFile = response.rows;
        // this.total = response.total;
        // this.loading = false;
      });
    },

    seriesIdlistProperty_fun (a) {
      console.log(a);
      this.propertyIdlistFile_req(a.id)
    },
    propertyIdlistFile_fun (a) {
      // 检查新项是否已存在于数组中  
      const exists = this.propertyIdlistFile_img_arr.some(item => item.id === a.id);
      // 如果新项不存在，则添加到数组中  
      if (!exists) {
        this.propertyIdlistFile_img_arr.push(a);
      } else {
        this.$message({
          message: '该项已存在于数组中，不会重复添加。',
          type: 'warning'
        });
      }
    },
    propertyIdlistFile_img_arr_fun (a) {
      console.log(a);
      // 使用 filter 方法来移除匹配的对象  
      this.propertyIdlistFile_img_arr = this.propertyIdlistFile_img_arr.filter(item => item !== a);
    },
    async downloadImage () {
      if (this.propertyIdlistFile_img_arr && this.propertyIdlistFile_img_arr.length > 0) {
      } else {
        this.$message({
          message: '请选择属性图片',
          type: 'warning'
        });
        return
      }
      const content = this.$refs.do_img
      const canvas = await html2canvas(content)
      const url = canvas.toDataURL('image/png')
      let arr_name = this.propertyIdlistFile_img_arr.map(item => item.name)
      let name_ = this.form.seriesName + this.form.propertyName + arr_name.join('_') + '.png'
      console.log(name_, 'name_');
      //图片名称 
      const filename = name_
      const link = document.createElement('a')
      console.log(url, 'urlurl');
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 解析图片，导出blob文件流
    async captureElementAsFile () {
      if (this.propertyIdlistFile_img_arr && this.propertyIdlistFile_img_arr.length > 0) {
      } else {
        this.$message({
          message: '请选择属性图片',
          type: 'warning'
        });
        return
      }
      // 元素节点
      const content = this.$refs.do_img
      const canvas = await html2canvas(content, {
        allowTaint: true, // 是否允许不同源的图片污染画布 （允许绘制）
        useCORS: true, // 是否尝试使用 CORS 从服务器加载图片 (允许跨域)
        // logging: true, // 启用日志记录以进行调试
        width: content.clientWidth * 1.005, // 设置图片宽度
        height: content.clientHeight * 1.005 // 设置图片高度
      })
      // 转blob文件流
      const blob = await new Promise(resolve => {
        canvas.toBlob(resolve, 'image/png')
      })
      // blob文件流转File对象
      let arr_name = this.propertyIdlistFile_img_arr.map(item => item.name)
      let name_ = this.form.seriesName + this.form.propertyName + arr_name.join('_') + '.png'
      this.form.message = name_

      const file = new File([blob], name_, { type: 'image/png' })
      this.uploadImg(file)
      // 转base64格式图片
      const base64 = canvas.toDataURL('image/png')
    },
    // 上传图片
    uploadImg (file) {
      const formData = new FormData();
      formData.append('file', file);
      system_common_upload(formData).then(response => {
        this.form.path = response.url
      });
    },
    realSrc (src) {
      if (!src) {
        return;
      }
      if (isExternal(src)) {
        return src;
      }
      return process.env.VUE_APP_BASE_API + src;
    },
    /** 查询保存图列表 */
    getList () {
      this.loading = true;
      listImages(this.queryParams).then(response => {
        this.imagesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        name: null,
        fileIds: [],
        path: null,
        message: null,
        createTime: null,
        seriesId: null,
        seriesName: null,
        fileId: null,
        fileName: null,
        propertyId: null,
        propertyName: null,
        remark1: null,
        remark2: null,
        remark3: null
      };
      // 查询系列对应的属性
      this.seriesIdlistProperty = [],
        // 查询的属性图片
        this.propertyIdlistFile = [],
        // 选中的图片
        this.propertyIdlistFile_img_arr = [],
        this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加保存图";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      getImages(id).then(response => {
        this.form = response.data;
        this.form.seriesId = Number(response.data.seriesId);
        this.form.fileIds = this.form.fileIds.split(",");
        this.form.path = null;
        this.open = true;
        this.title = "修改保存图";
      });
    },
    /** 提交按钮 */
    submitForm () {
      if (!this.form.name) {
        this.$message({
          message: '名称不能为空',
          type: 'warning'
        });
        return
      }
      if (!this.form.path) {
        this.$message({
          message: '请点击保存图片',
          type: 'warning'
        });
        return
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.propertyIdlistFile_img_arr, 'this.propertyIdlistFile_img_arr');
          this.form.propertyId = this.propertyIdlistFile_img_arr.map(item => item.propertyId).join('_')
          this.form.propertyName = this.propertyIdlistFile_img_arr.map(item => item.propertyName).join('_')
          this.form.fileId = this.propertyIdlistFile_img_arr.map(item => item.id).join('_')
          this.form.fileName = this.propertyIdlistFile_img_arr.map(item => item.name).join('_')
          this.form.fileIds = this.form.fileIds.join(",");
          if (this.form.id != null) {
            updateImages(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              console.log(response, 'responseresponse');
              this.getList();
            });
          } else {

            addImages(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除保存图编号为"' + ids + '"的数据项？').then(function () {
        return delImages(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/images/export', {
        ...this.queryParams
      }, `images_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.property_css {
  color: #999;
  display: flex;
  .property_css_1 {
    color: #999;
  }
  .property_css_2 {
    color: #999;
    margin-left: 13px;
    .property_css_2_1 {
      color: #999;
    }
  }
  .property_css_3 {
    color: #999;
    margin-left: 30px;
    display: flex;
    flex-flow: wrap;
    width: 300px;
    .property_css_3_1 {
      color: #999;
    }
    .property_css_3_2 {
      color: #999;
      color: #999;
      text-align: center;
      border: 1px solid #888;
      margin: 5px;
      border-radius: 5px;
      .property_css_3_2_1 {
        color: #999;
        margin: 5px;
      }
      .property_css_3_2_2 {
        color: #999;
      }
    }
  }
  .property_css_4 {
    color: #999;
    display: flex;
    flex-flow: row;
    .property_css_4_1 {
      color: #999;
    }
    .property_css_4_2 {
      color: #999;
      text-align: center;
      border: 1px solid #888;
      margin: 5px;
      border-radius: 5px;
      .property_css_4_2_1 {
        color: #999;
        margin: 5px;
      }
      .property_css_4_2_2 {
        color: #999;
      }
    }
  }
}
.property_cs1 {
  color: #999;
  margin: 5px;
}
.property_cs2 {
  color: #999;
  margin: 5px;
}
.property_cs3 {
  color: #999;
}
</style>
